package com.bort.system.common;

import com.bort.system.controller.DeskController;
import com.bort.system.scheduler.ClientRefreshScheduler;
import com.bort.system.serial.SerialManager;
import javafx.application.Platform;
import javafx.stage.Stage;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;

public class CloseSystemActionListener implements ActionListener {

    ClientRefreshScheduler scheduler;
    Stage stage;

    TrayIcon icon;

    public CloseSystemActionListener(Stage primaryStage, ClientRefreshScheduler pScheduler,TrayIcon trayIcon) {
        stage = primaryStage;
        scheduler = pScheduler;
        icon = trayIcon;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Platform.setImplicitExit(true);
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                stage.close();
                scheduler.cancelAllTask();
                SerialManager serialManager = SerialManager.getInstance();
                if(serialManager.openingPort != null && serialManager.openingPort.isOpen()){
                    serialManager.openingPort.closePort();
                }
                SystemTray.getSystemTray().remove(icon);
                Iterator<Integer> keyItr = DataContainer.deskCtrlMap.keySet().iterator();
                while (keyItr.hasNext()){
                    Integer key = keyItr.next();
                    DeskController ctrl = DataContainer.deskCtrlMap.get(key);
                    ctrl.stopAnimate();
                }
            }
        });
    }
}
